package org.wzq.android_api;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

import java.io.IOException;

/**
 *
 */
public class Act_Uninstall extends Activity {
    Context mctx;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_uninstall);
        mctx = this;

        findViewById(R.id.btn_uninstall_normal).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                uninstall_normal("org.wzq.android_api");
            }
        });

        findViewById(R.id.btn_uninstall_silent).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // Toast.makeText(mctx, "未支持", Toast.LENGTH_SHORT).show();
                uninstall_silently_test1("org.wzq.android_api");
            }
        });
    }

    /**
     * OK 4.0.x root权限
     */
    private boolean uninstall_silently_test1(String pkgName) {
        android.content.pm.PackageManager pm = getPackageManager();
        try {
            PackageInfo info = pm.getPackageInfo(pkgName, 0);
            if (info != null) {
                final String command = "pm uninstall -k " + pkgName;
                Process proc = Runtime.getRuntime().exec(new String[]{"su", "-c", command});
                proc.waitFor();
                return true;
            } else {
                Toast.makeText(mctx, "软件不存在:" + pkgName, Toast.LENGTH_SHORT).show();
            }
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return false;
    }

    private void uninstall_normal(String packageName) {
        Application app = getApplication();
        android.content.pm.PackageManager pm = app.getPackageManager();
        try {
            PackageInfo info = pm.getPackageInfo(packageName, 0);
            if (info != null) {
                Uri uri = Uri.parse("package:" + packageName);
                Intent intent = new Intent(Intent.ACTION_DELETE, uri);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                app.startActivity(intent);
            }
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
    }
}
